import { adminMenus } from '@/api/system/menu'
import { constantRouterComponents, constantRouterIcon } from './constantRouterComponents'
import router from '@/router/index'
import { constantRouter } from '@/router/index'
import { RouteRecordRaw } from 'vue-router'

/**
 * 格式化 后端 结构信息并递归生成层级路由表
 *
 * @param routerMap
 * @param parent
 * @returns {*}
 */
export const routerGenerator = (routerMap, parent?): any[] => {
    return routerMap.map(item => {
        const currentRouter: any = {
            // 路由地址 动态拼接生成如 /dashboard/workplace
            path: `${ parent && parent.path || '' }/${ item.path }`,
            // 路由名称，建议唯一
            name: item.name || '',
            // 该路由对应页面的 组件
            component: constantRouterComponents[item.component],
            // meta: 页面标题, 菜单图标, 页面权限(供指令权限用，可去掉)
            meta: {
                ...item.meta,
                label: item.meta.title,
                icon: constantRouterIcon[item.meta.icon] || null,
                permission: item.meta.permission || null
            }
        }
        // 为了防止出现后端返回结果不规范，处理有可能出现拼接出两个 反斜杠
        currentRouter.path = currentRouter.path.replace('//', '/')
        // 重定向
        item.redirect && (currentRouter.redirect = item.redirect)
        // 是否有子菜单，并递归处理
        if (item.children && item.children.length > 0) {
            // Recursion
            currentRouter.children = routerGenerator(item.children, currentRouter)
        }
        return currentRouter
    })
}


/**
 * 动态生成菜单
 * @param token
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = (): Promise<RouteRecordRaw[]> => {
    return new Promise((resolve, reject) => {
        adminMenus()
            .then((result) => {
                const routeList = routerGenerator(result)
                const asyncRoutesList = [...constantRouter, ...routeList]
                asyncRoutesList.forEach(item => {
                    router.addRoute(item)
                })
                resolve(asyncRoutesList)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
